local template = require "resty.template"
local math_ceil=math.ceil
local math_floor=math.floor
local gsub=ngx.re.gsub
local page_M = {}

function page_M:new(total,pre_page,current_page,url)
	local total_page = math_ceil(total/pre_page);

	current_page=current_page or 1;
	current_page=tonumber(current_page)

	if current_page>total_page then
		current_page=total_page
	end	

	if current_page<1 then
		current_page=1
	end

	local start = (current_page-1)*pre_page;

	local  obj = {
		total_page=total_page,
		current_page=current_page,
		start=start,
		pre_page=pre_page,
		urlstr=url,
		min=1,
		max=1
	}

	setmetatable(obj,{__index=self})
	return obj
end

function page_M:limit()
	return self.start..","..self.pre_page
end

function page_M:url(page_num)
	return gsub(self.urlstr, ngx.escape_uri(":page:"),page_num)
end

function page_M:get_nums()
	local numbers = {}
	local num_range=10;

	local page_num2=math_ceil(self.current_page/num_range)

	local start_num=(page_num2-1)*num_range+1;
	local end_num=start_num+num_range-1

	for i=start_num,end_num do
		if i>=1 and i<=self.total_page then
			numbers[#numbers+1]=i
		end
	end

	if _G.next(numbers) then
		self.min=numbers[1]-1;
		self.max=numbers[#numbers]+1;
	else
		self.min=1
		self.max=1
	end

	return numbers
end

function page_M:render()
	return template.compile("page.html", { pageobj = self })
end
return page_M
